package com.leetcode.剑指offer第2版;

/**
 * @author 覃国强
 * @date 2022-03-03 13:18
 */
public class 剑指Offer_45_把数组排成最小的数 {

  public static void main(String[] args) {
    int[] nums = {10, 2};
    Solution solution = new Solution();
    String number = solution.minNumber(nums);
    System.out.println(number);
  }

  static
  class Solution {
    public String minNumber(int[] nums) {
      bubbleSort(nums);
      StringBuilder sb = new StringBuilder();
      for (int num : nums) {
        sb.append(num);
      }
      return sb.toString();
    }

    private void bubbleSort(int[] nums) {
      int lastSwapIndex = nums.length - 1;
      while (lastSwapIndex != -1) {
        int currentSwapIndex = -1;
        for (int i = 0; i < lastSwapIndex; ++i) {
          if (needSwap(nums[i], nums[i + 1])) {
            swap(nums, i, i + 1);
            currentSwapIndex = i;
          }
        }
        lastSwapIndex = currentSwapIndex;
      }
    }

    private boolean needSwap(int a, int b) {
      int compare = (String.valueOf(a) + b).compareTo(String.valueOf(b) + a);
      return compare > 0;
    }

    private void swap(int[] nums, int i, int j) {
      int temp = nums[i];
      nums[i] = nums[j];
      nums[j] = temp;
    }
  }

}
